package com.itqf.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * projectName: gp_manage
 *
 * @author: 赵伟风
 * time: 2021/8/17 11:15
 * description: 字符串数组字段 转成整数数组
 */
@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringToIntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {

    private static  final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * insert update 会触发， 将插入的整数数组 转成字符串存入数据库
     * @param preparedStatement
     * @param i
     * @param integers
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {

        //1.整数数组转成字符串
        String idsStr = null;
        try {
            idsStr = objectMapper.writeValueAsString(integers);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //2.将字符串放在占位符上
        preparedStatement.setObject(i,idsStr);
    }

    /**
     * select 会触发，查询的字符串结果转成整数数组，赋值给实体类的属性
     * @param resultSet
     * @param s
     * @return
     * @throws SQLException
     */
    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String s) throws SQLException {

        //1.获取结果集的数据
        String idsStr = resultSet.getString(s);
        //2.转成数组返回

        Integer[] ids = null;

        try {
            ids = objectMapper.readValue(idsStr, Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ids;
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int i) throws SQLException {


        //1.获取结果集的数据
        String idsStr = resultSet.getString(i);
        //2.转成数组返回

        Integer[] ids = null;

        try {
            ids = objectMapper.readValue(idsStr, Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ids;
    }

    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {

        //1.获取结果集的数据
        String idsStr = callableStatement.getString(i);
        //2.转成数组返回

        Integer[] ids = null;

        try {
            ids = objectMapper.readValue(idsStr, Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ids;
    }
}
